Skip to main content

Which Algo to Select, Pattern Based Answer

Source

If​

Input Array is Sorted Then​

Asked for All permutations/subsets Then​

Given a Tree Then​

  • DFS
    • inorder,preorder, postorder
  • BFS

Given a Graph Then​

  • DFS
  • BFS

Given a Linked List Then​

Recursion is Banned Then​

Must Solve In-place Then​

  • Swap corresponding values
  • Store one or more different values in the same pointer

Asked for maximum/minimum of Not-contiguous sub-array/subset/options Then​

Asked for top/least K Items Then​

Asked for Common Strings Then​

Asked Contiguous Sub-string with X Condition​

Asked Contiguous Sub-array Sum with X Condition​

Next/Prev Greater or Smaller Element​

Else​

  • Map/Set for O(1) time & O(n) space
  • Sort input for O(nlogn) time and O(1) space